﻿using Inovout.Component;
using Inovout.Data.Service;
using Inovout.Organization.Domain;
using Inovout.People.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Inovout.Cloud.Messager.WebPage.Models
{
    public class PositionLogic : RepositoryService<Position>
    {
        DepartmentLogic departmentlogic = new DepartmentLogic();
        PersonLogic personlogic = new PersonLogic();
        IRepositoryService<Position> Service = ComponentRegistry.Resolve<IRepositoryService<Position>>();
        public void HandlePosition()
        {
            List<Person> persons = personlogic.GetAllPerson();
            List<Position> positions = GetAllPostion();
            List<Persondata> dPersons = personlogic.GetALLPerson(personlogic.GetPersonData());
            foreach (Person person in persons)
            {
                Persondata data = dPersons.Where(c => c.userid == person.UserId && c.name == person.Name && c.departmentid == person.OrganizationUnitId).Select(c => c).SingleOrDefault();
                if (positions.Count == 0)
                {
            if (data.office.Length > 0)
            {
                    Position postion = new Position();
                    postion.Person = person;
                    postion.Name = data.office;
                    InsertPostion(postion);
            }
                }
                else
                {
                    List<Position> positiones = positions.Where(c => c.Person == person).Select(c => c).ToList();
                    foreach (Position position in positiones)
                    {
                        if (position == null)
                        {
                            position.Person = person;
                            position.Name = data.office;
                            InsertPostion(position);
                        }
                        else
                        {
                            positions.Remove(position);
                            position.Person = person;
                            position.Name = data.office;
                            InsertPostion(position);
                        }
                    }
                }
            }
            RemovePosition(positions);
        }
        public void InsertPostion(Position postion)
        {
            Service.Save(postion);
        }
        public void RemovePosition(List<Position> positions)
        {
            foreach (Position position in positions)
            {
                Service.Delete(position);
            }
        }
        public List<Position> GetAllPostion()
        {
            return Service.Query().ToList();
        }
    }
}